package com.cassiopae.task;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.MessagingException;

import com.cassiopae.dao.ProfileDaoImpl;
import com.cassiopae.entity.Profile;
import com.cassiopae.entity.User;
import com.cassiopae.util.CassiopaeDumpConstant;
import com.cassiopae.util.CassiopaeDumpUtil;
import com.mysql.jdbc.StringUtils;

public class DumpTask extends Thread {
	
	private String fichierJoint;

	private String fileName;
	private String schemaSource;
	private Profile profile;
	private String dumpType;
	
	private String otherSourceSchemaInput;
	private Profile otherProfile;
	//private String pathPropertyAntFile;
	public static final String DUMPTYPE_DUMP = "DUMP";
	public static final String DUMPTYPE_DATAPUMP = "DATAPUMP";
	private ProfileDaoImpl profileDaoImpl = new ProfileDaoImpl();

	private User user;

	public DumpTask(String _fileName, String _schemaSource, Profile _profile, String _dumpType, User _user){
		fileName = _fileName;
		schemaSource = _schemaSource;
		profile = _profile;
		dumpType = _dumpType;
		user = _user;
	}

	@Override
	public void run() {
		SimpleDateFormat sp = new SimpleDateFormat("ddMMyy_HH_mm_ss");
		String outputName = sp.format( new Date() );
		outputName = profile.getSchemaCible()+"_"+profile.getDatabaseCible()+"_"+outputName;
		String command = null;

		if("V4".equalsIgnoreCase( profile.getAppliVersion() ) 
				&& "BACK".equalsIgnoreCase( profile.getImpSchema() ) 
				&& DUMPTYPE_DATAPUMP.equalsIgnoreCase( dumpType)
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput ) ){
			command = "datapump_ImportKSIOP_v4_NDE.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "+schemaSource
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if("V4".equalsIgnoreCase(profile.getAppliVersion()) 
				&& "BACK".equalsIgnoreCase( profile.getImpSchema()) 
				&& DUMPTYPE_DUMP.equalsIgnoreCase(dumpType)
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput ) ){
			command = "ImportKSIOP_V4.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "+schemaSource
			        +" > C:\\Cassiopae\\datapump\\dump\\"+outputName+".txt";
		}else if("V3".equalsIgnoreCase( profile.getAppliVersion() ) 
				&& "BACK".equalsIgnoreCase( profile.getImpSchema() ) 
				&& DUMPTYPE_DATAPUMP.equalsIgnoreCase( dumpType)
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput )
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput ) ){
			command = "datapump_ImportKSIO.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "+schemaSource
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if("V3".equalsIgnoreCase( profile.getAppliVersion() ) 
				&& "BACK".equalsIgnoreCase( profile.getImpSchema() ) 
				&& DUMPTYPE_DUMP.equalsIgnoreCase( dumpType)
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput ) ){
			command = "ImportKSIOP.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "+schemaSource
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if("V3".equalsIgnoreCase( profile.getAppliVersion() ) 
				&& "FRONT".equalsIgnoreCase( profile.getImpSchema() ) 
				&& DUMPTYPE_DUMP.equalsIgnoreCase( dumpType) 
				&& otherProfile == null 
				&& StringUtils.isNullOrEmpty( otherSourceSchemaInput ) ){
			command = "ImportANDRO.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "+schemaSource
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if(otherProfile != null 
				&& !StringUtils.isNullOrEmpty( otherSourceSchemaInput )
				&& otherProfile.getImpSchema() != profile.getImpSchema()
				&& "V4".equalsIgnoreCase(profile.getAppliVersion() )
				&& otherProfile.getAppliVersion().equals(profile.getAppliVersion())
				&& DUMPTYPE_DATAPUMP.equalsIgnoreCase( dumpType) ){
			command = "datapump_ImportKSIOPANDRO_V4.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "
					+otherProfile.getSchemaCible()+" "
					+otherProfile.getPassword()+" "
					+schemaSource+" "
					+otherSourceSchemaInput
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if(otherProfile != null 
				&& !StringUtils.isNullOrEmpty( otherSourceSchemaInput )
				&& otherProfile.getImpSchema() != profile.getImpSchema()
				&& "V3".equalsIgnoreCase(profile.getAppliVersion() ) 
				&& otherProfile.getAppliVersion().equals(profile.getAppliVersion())
				&& DUMPTYPE_DATAPUMP.equalsIgnoreCase( dumpType) ){
			command = "datapump_ImportKSIOPANDRO.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "
					+otherProfile.getSchemaCible()+" "
					+otherProfile.getPassword()+" "
					+schemaSource+" "
					+otherSourceSchemaInput
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if(otherProfile != null 
				&& !StringUtils.isNullOrEmpty( otherSourceSchemaInput )
				&& otherProfile.getImpSchema() != profile.getImpSchema()
				&& "V4".equalsIgnoreCase(profile.getAppliVersion() )
				&& otherProfile.getAppliVersion().equals(profile.getAppliVersion())
				&& DUMPTYPE_DUMP.equalsIgnoreCase( dumpType) ){
			command = "importKSIOPANDRO_V4.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "
					+otherProfile.getSchemaCible()+" "
					+otherProfile.getPassword()+" "
					+schemaSource+" "
					+otherSourceSchemaInput
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}else if(otherProfile != null 
				&& !StringUtils.isNullOrEmpty( otherSourceSchemaInput )
				&& otherProfile.getImpSchema() != profile.getImpSchema()
				&& "V3".equalsIgnoreCase(profile.getAppliVersion() ) 
				&& otherProfile.getAppliVersion().equals(profile.getAppliVersion())
				&& DUMPTYPE_DUMP.equalsIgnoreCase( dumpType) ){
			command = "importKSIOPANDRO.bat "+profile.getDatabaseCible()+" "
					+fileName+" "
					+profile.getSchemaCible()+" "
					+profile.getPassword()+" "
					+otherProfile.getSchemaCible()+" "
					+otherProfile.getPassword()+" "
					+schemaSource+" "
					+otherSourceSchemaInput
					+" > C:\\Cassiopae\\datapump\\"+outputName+".txt";
		}
		
		if( command != null){
			executeCommand(command);
			
			profile.setStatus(false);
			profileDaoImpl.updateStatusAndEndTime(profile);
			
			if( otherProfile != null ){
				otherProfile.setStatus(false);
				profileDaoImpl.updateStatusAndEndTime(otherProfile);
			}
			
			MailTask mailTask = new MailTask(profile);
			try {
				mailTask.sendReportMessage(MailTask.MESSAGE_SUBJECT_REPORT, fichierJoint , profile,  user);
			} catch (MessagingException e) {
				
			}
		}

	}

	
private void executeCommand(String command) {
		String[] cmd = {"cmd",};

		Process p;
		try {
			p = Runtime.getRuntime().exec(cmd);
			SimpleDateFormat sp = new SimpleDateFormat("ddMMyy_HH_mm_ss");
			String outputName = sp.format( new Date() );
			fichierJoint = "c:/temp/sortie"+outputName+".txt";
			File f = new File(fichierJoint);
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
		    new Thread(new SyncPipe(p.getInputStream(), fos)).start();
		    
		    CassiopaeDumpUtil dumpUtil = new CassiopaeDumpUtil();
			OutputStream out = p.getOutputStream();
			PrintWriter printer = new PrintWriter(out);
			printer.println("cd "+ dumpUtil.getApplicationValueString(CassiopaeDumpConstant.KEY_PROPERTY_BAT_DIRECTORY, CassiopaeDumpConstant.CONFIG_FILE_APPLICATION));
			
			if( "11".equals( profile.getDbVersion() ) ){
				printer.println("SET ORABIN11="+ dumpUtil.getApplicationValueString(CassiopaeDumpConstant.KEY_PROPERTY_ORACLE_HOME_BIN_11, CassiopaeDumpConstant.CONFIG_FILE_APPLICATION));
			}else if( "10".equals( profile.getDbVersion() ) ){
				printer.println("SET ORABIN10="+ dumpUtil.getApplicationValueString(CassiopaeDumpConstant.KEY_PROPERTY_ORACLE_HOME_BIN_10, CassiopaeDumpConstant.CONFIG_FILE_APPLICATION));
			}
			
			printer.println(command);
			printer.close();
			int returnCode = p.waitFor();

			System.out.println("Return Code : " + returnCode);

		} catch (Exception e) {
		}
	}

	public String getOtherSourceSchemaInput() {
	return otherSourceSchemaInput;
}

public void setOtherSourceSchemaInput(String otherSourceSchemaInput) {
	this.otherSourceSchemaInput = otherSourceSchemaInput;
}

	public Profile getOtherProfile() {
	return otherProfile;
}

public void setOtherProfile(Profile otherProfile) {
	this.otherProfile = otherProfile;
}

	public String getSchemaSource() {
	return schemaSource;
}

public void setSchemaSource(String schemaSource) {
	this.schemaSource = schemaSource;
}

public Profile getProfile() {
	return profile;
}

public void setProfile(Profile profile) {
	this.profile = profile;
}

	class SyncPipe implements Runnable
	{
		public SyncPipe(InputStream istrm, OutputStream ostrm) {
			istrm_ = istrm;
			ostrm_ = ostrm;
		}
		public void run() {
			try
			{
				final byte[] buffer = new byte[1024];
				for (int length = 0; (length = istrm_.read(buffer)) != -1; )
				{
					ostrm_.write(buffer, 0, length);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		private final OutputStream ostrm_;
		private final InputStream istrm_;
	}
}
